#include <func.h>

int display();
int main()
{
    // 查看共享内存信息；

    int ret = display();
    ERROR_CHECK(ret, -1, "A1 display");

    return 1;
}

int display()
{
    // 1.从共享内存中读取数据
    // 没有消息就等待有消息就读取，类似消费者；
    // 创建一个信号量集 如果共享内存有数据就读取。如果共享内存没有数据就阻塞；
    int semid = semget(2000, 1, IPC_CREAT | 0666);
    ERROR_CHECK(semid, -1, "A1 semget");
    semctl(semid, 0, SETVAL, 0); // 信号量初始值设为0
    // 设置信号量，测试并取资源，类似消费者操作
    struct sembuf P;
    P.sem_num = 0;
    P.sem_op = -1;
    P.sem_flg = SEM_UNDO;
    printf("=========================A1===============\n");
    while (1)
    {
        semop(semid, &P, 1);
        int shmid = shmget(1001, 4096, IPC_CREAT | 0600);
        ERROR_CHECK(shmid, -1, "shmid");
        char *pid = (char *)shmat(shmid, NULL, 0);
        ERROR_CHECK(pid, (void *)-1, "shmat");

        int type = 0;
        sscanf(pid, "%*d %d", &type);
        switch (type)
        {
        case 1:
        {
            // 从B来的消息
            printf("<<<<<<<<<<<<<<<<<<<<<receive<<<<<<<<<<<<<<<<\n");
            struct tm *ptm = NULL;
            time_t tmp = 0;
            char ss[512] = {0};
            sscanf(pid, "%ld", &tmp);
            sscanf(pid, "%*d %*d %[^\n]", ss);
            ptm = gmtime(&tmp);
            printf("%4d-%02d-%02d %02d:%02d:%02d\n",
                   ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday,
                   ptm->tm_hour, ptm->tm_min, ptm->tm_sec);

            puts(ss);
            printf("\n");
            // 清空共享内存数据；
            memset(pid, 0, 4096);
            break;
        }
        case 2:
        {
            printf("bye bye\n");
            shmdt(pid);
            shmctl(shmid, IPC_RMID, NULL);
            exit(0);
            break;
        }

        case 3:
        {

            printf(">>>>>>>>>  send  >>>>>>>>>>>\n");
            struct tm *ptm3 = NULL;
            time_t tmp3 = 0;
            char ss3[512] = {0};
            sscanf(pid, "%ld", &tmp3); // 读取消息中的时间信息
            sscanf(pid, "%*d %*d %[^\n]", ss3);
            ptm3 = gmtime(&tmp3);
            printf("%4d-%02d-%02d %02d:%02d:%02d\n",
                   ptm3->tm_year + 1900, ptm3->tm_mon + 1, ptm3->tm_mday,
                   ptm3->tm_hour, ptm3->tm_min, ptm3->tm_sec);
            puts(ss3);
            printf("\n");
            // 清空共享内存中的数据
            memset(pid, 0, 4096);
            break;
        }
        default:
        {
            printf("sonething wrong!\n");
            break;
        }
        }
    }
}